﻿using LogisticsTrackingWebApi_V2.Services;

namespace LogisticsTrackingWebApi_V2.ServicesImpl
{

    /// <summary>
    /// 物流提供者工厂实现
    /// </summary>
    public class LogisticsProviderFactory : ILogisticsProviderFactory
    {
        private readonly IEnumerable<ILogisticsProvider> _providers;

        // 通过依赖注入获取所有ILogisticsProvider的实现
        public LogisticsProviderFactory(IEnumerable<ILogisticsProvider> providers)
        {
            _providers = providers;
        }

        public ILogisticsProvider GetProvider(string companyCode)
        {
            var provider = _providers.FirstOrDefault(p =>
                p.CompanyCode.Equals(companyCode, StringComparison.OrdinalIgnoreCase));

            if (provider == null)
            {
                throw new KeyNotFoundException($"不支持的物流公司代码: {companyCode}");
            }

            return provider;
        }

        public IEnumerable<ILogisticsProvider> GetAllProviders()
        {
            return _providers.OrderBy(p => p.CompanyName);
        }

        public ILogisticsProvider? GuessProvider(string trackingNumber)
        {
            // 简单的运单号规则匹配，实际项目中可能更复杂
            if (!string.IsNullOrEmpty(trackingNumber))
            {
                // 顺丰通常以SF开头或13位数字
                if (trackingNumber.StartsWith("SF", StringComparison.OrdinalIgnoreCase) ||
                    trackingNumber.Length == 13 && long.TryParse(trackingNumber, out _))
                {
                    return GetProvider("SF");
                }

                // 京东物流通常是15位数字
                if (trackingNumber.Length == 15 && long.TryParse(trackingNumber, out _))
                {
                    return GetProvider("JD");
                }

                // 圆通通常是10位或12位数字
                if ((trackingNumber.Length == 10 || trackingNumber.Length == 12) &&
                    long.TryParse(trackingNumber, out _))
                {
                    return GetProvider("YTO");
                }
            }

            return null;
        }
    }

}
